package net.zigin.nhi.could.waste.service.impl;

import net.zigin.commons.util.AssertUtil;
import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.ReflectUtil;
import net.zigin.commons.util.StringUtil;
import net.zigin.nhi.could.waste.aop.LoginAspect;
import net.zigin.nhi.could.waste.vo.TokenInfoBo;
import net.zigin.nhi.could.waste.dao.SysMenuMapper;
import net.zigin.nhi.could.waste.dao.SysRoleMapper;
import net.zigin.nhi.could.waste.dao.SysUserHospitalMapper;
import net.zigin.nhi.could.waste.dto.SysRoleDto;
import net.zigin.nhi.could.waste.service.SysUserService;
import net.zigin.nhi.could.waste.vo.SysMenuVo;
import net.zigin.nhi.could.waste.vo.SysRoleVo;
import net.zigin.nhi.could.waste.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.zigin.nhi.could.waste.dao.BaseMapper;
import net.zigin.nhi.could.waste.model.SysRole;
import net.zigin.nhi.could.waste.service.SysRoleService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*#################################################################*
# 说明:以下代码通过哲勤代码生成工具自动生成    
# 工具:GeneratorCode
# 作者:mgw1986                                                  
# 生成时间:2021-9-7 19:08:55                                               
##################################################################*/


/**
 * SysRole服务实现类
 *
 * @author mgw1986
 * @version V1.0
 * @ClassName: SysRoleServiceImpl
 * @date 2021-9-7 19:08:55
 */
@Service
public class SysRoleServiceImpl extends AbstractServiceImpl<SysRole, String> implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserHospitalMapper sysUserHospitalMapper;

    @Override
    public BaseMapper<SysRole, String> getMapper() {
        return sysRoleMapper;
    }

    @Override
    public void concatMenu(String roleId, List<String> menuIds) {
        // 清掉之前保存的
        sysRoleMapper.removeMenu(roleId);
        menuIds.forEach(menuId -> {
            String roleMenu = sysRoleMapper.readRoleMenu(roleId, menuId);
            if (roleMenu == null) {
                sysRoleMapper.writeRoleMenu(StringUtil.get32UUID(), roleId, menuId);
            }
        });
    }

    @Override
    public void concatUser(List<String> roleIds, String userId) {
        // 清掉之前的数据
        sysRoleMapper.removeUser(userId);
        roleIds.forEach(roleId -> {
            String roleUser = sysRoleMapper.readRoleUser(roleId, userId);
            if (roleUser == null) {
                sysRoleMapper.writeRoleUser(StringUtil.get32UUID(), userId, roleId);
            }
        });
    }

    @Override
    public String saveOrUpdate(SysRoleDto roleDto) {
        SysUserVo currentUser = sysUserService.getCurrentUser();
        String hospitalBaseId = sysUserHospitalMapper.getHospitalBaseIdBySysUserId(currentUser.getId());
        roleDto.setHospitalBaseId(hospitalBaseId);
        if (StringUtil.isNullOrEmpty(roleDto.getSysFlag())) {
            roleDto.setSysFlag(currentUser.getType());
        }
        TokenInfoBo tokenInfo = LoginAspect.getTokenInfo();
        if (StringUtil.isNullOrEmpty(roleDto.getId())) {
            AssertUtil.isNull(roleDto, "角色信息不能为空");
            AssertUtil.isNull(roleDto.getCode(), "角色编码不能为空");
            AssertUtil.isNull(roleDto.getName(), "角色名不能为空");
            AssertUtil.isNull(roleDto.getSysFlag(), "系统标识不能为空");
            roleDto.setId(StringUtil.get32UUID());
            roleDto.setCreateTime(new Date());
            roleDto.setModifyTime(new Date());
            roleDto.setCreateUser(tokenInfo.getLoginName());
            SysRole role = ReflectUtil.copyProperties(roleDto, SysRole.class);
            sysRoleMapper.insert(role);
            return role.getId();
        }
        roleDto.setModifyTime(new Date());
        roleDto.setModifyUser(tokenInfo.getLoginName());
        SysRole role = ReflectUtil.copyProperties(roleDto, SysRole.class);
        sysRoleMapper.updateByPrimaryKeySelective(role);
        return role.getId();
    }

    @Override
    public List<SysRoleVo> getRoleList(SysRoleDto roleDto) {
        Map<String, Object> paramMap = getRoleParams(roleDto);
        List<SysRole> roles;
        if (roleDto.getIsPage()) {
            roles = sysRoleMapper.selectListByPage(paramMap);
        } else {
            // todo 不反回禁用的角色
            //paramMap.put("isFreeze", 0);
            roles = sysRoleMapper.selectListByCondition(paramMap);
        }
        List<SysRoleVo> roleVos = ReflectUtil.copyProperties(roles, SysRoleVo.class);
        if (roleVos == null) {
            return new ArrayList<>();
        }
        roleVos.forEach(roleVo -> {
            List<SysMenuVo> menuVos = sysMenuMapper.infoByRoleId(roleVo.getId());
            roleVo.setMenuVos(menuVos);
        });
        return roleVos;
    }

    @Override
    public Integer getRoleCount(SysRoleDto roleDto) {
        Map<String, Object> paramMap = getRoleParams(roleDto);
        return sysRoleMapper.selectCount(paramMap);
    }

    private Map<String, Object> getRoleParams(SysRoleDto roleDto) {
        SysUserVo currentUser = sysUserService.getCurrentUser();
        String hospitalBaseId = sysUserHospitalMapper.getHospitalBaseIdBySysUserId(currentUser.getId());
        if (StringUtil.isNullOrEmpty(roleDto.getSysFlag())) {
            roleDto.setSysFlag(currentUser.getType());
        }
        if (!StringUtil.isNullOrEmpty(roleDto.getDoublePlatformFlag())) {
            if (roleDto.getDoublePlatformFlag().equals("1")) {
                roleDto.setSysFlag("");
            } else {
                roleDto.setDoublePlatformFlag("");
            }
        }
        return ParamsMapUtil.getInstance()
                .addParam("hospitalBaseId", hospitalBaseId)
                .addParam("doublePlatformFlag", roleDto.getDoublePlatformFlag())
                .addParam("sysFlag", roleDto.getSysFlag())
                .addParam("code", roleDto.getCode())
                .addParam("workGroup", roleDto.getWorkGroup())
                .addParam("sysFlag", roleDto.getSysFlag())
                .addParam("name", roleDto.getName())
                .addParam("pageIndex", roleDto.getPageIndex())
                .addParam("pageSize", roleDto.getPageSize());
    }

    @Override
    public List<SysRoleVo> infoByUserId(String userId) {
        List<SysRole> sysRoles = sysRoleMapper.infoByUserId(userId);
        if (sysRoles.isEmpty()) {
            return new ArrayList<>();
        }
        return ReflectUtil.copyProperties(sysRoles, SysRoleVo.class);
    }

    @Override
    public SysRoleVo getInfoById(String id) {
        SysRole role = sysRoleMapper.selectByPrimaryKey(id);
        SysRoleVo roleVo = ReflectUtil.copyProperties(role, SysRoleVo.class);
        List<SysMenuVo> sysMenuVos = sysMenuMapper.infoByRoleId(id);
        roleVo.setMenuVos(sysMenuVos);
        return roleVo;
    }

    @Override
    public void concatUser(String userId, int type) {
        String roleId = "";
        if (type == 0) {
            roleId = sysRoleMapper.getIdByCode("h001");
        } else if (type == 1) {
            roleId = sysRoleMapper.getIdByCode("s001");
        } else if (type == 2) {
            roleId = sysRoleMapper.getIdByCode("d001");
        } else {
            roleId = sysRoleMapper.getIdByCode("a001");
        }
        sysRoleMapper.writeRoleUser(StringUtil.get32UUID(), userId, roleId);
    }

    @Override
    public Boolean judgeRemove(String id) {
        // 查看该角色下有咩有人员 就是看 sys_user_role 关联表
        Integer userCount = sysRoleMapper.checkRoleUser(id);
        return userCount == 0;
    }

    @Override
    public void remove(String id) {
        sysRoleMapper.deleteByPrimaryKey(id);
        sysRoleMapper.removeMenu(id);
    }
}